package yb.ecp.fast.infra.bus;

import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RefreshScope
public class GuavaLogEvent {

    @Resource(name = "gwRedisTemplate")
    private RedisTemplate redisTemplate;

    @Value("${fast.auth.login.sessionTime:3000}")
    private Long sessionTime;
    private final RateLimiter rateLimiter = RateLimiter.create(10);

    @Subscribe
    public void subscribe(String token) {
        boolean tryAcquire = rateLimiter.tryAcquire(0, TimeUnit.SECONDS);
        if (tryAcquire) {
            redisTemplate.expire(token, sessionTime, TimeUnit.SECONDS);
        }
    }

}
